# Author: zhaozeliang
# Date: 2025-09-06

from rest_framework import status, generics, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from .models import User, RiskAssessment
import logging

logger = logging.getLogger(__name__)
from .serializers import (
    UserRegistrationSerializer,
    UserLoginSerializer,
    UserProfileSerializer,
    PasswordChangeSerializer,
    RiskAssessmentSerializer
)

@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def register(request):
    """用户注册"""
    logger.debug(f"注册请求数据: {request.data}")
    serializer = UserRegistrationSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.save()
        token, created = Token.objects.get_or_create(user=user)
        logger.info(f"用户注册成功: {user.username}")
        return Response({
            'message': '注册成功',
            'token': token.key,
            'user_id': user.id,
            'username': user.username
        }, status=status.HTTP_201_CREATED)
    else:
        logger.error(f"注册验证失败: {serializer.errors}")
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def login_view(request):
    """用户登录"""
    serializer = UserLoginSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.validated_data['user']
        login(request, user)
        token, created = Token.objects.get_or_create(user=user)
        
        # 使用UserProfileSerializer序列化用户数据
        user_serializer = UserProfileSerializer(user)
        
        return Response({
            'message': '登录成功',
            'token': token.key,
            'user': user_serializer.data
        }, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def logout_view(request):
    """用户登出"""
    try:
        # 删除用户的token
        request.user.auth_token.delete()
    except:
        pass
    logout(request)
    return Response({'message': '登出成功'}, status=status.HTTP_200_OK)

class UserProfileView(generics.RetrieveUpdateAPIView):
    """用户资料视图"""
    serializer_class = UserProfileSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_object(self):
        return self.request.user

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def change_password(request):
    """修改密码"""
    serializer = PasswordChangeSerializer(data=request.data, context={'request': request})
    if serializer.is_valid():
        serializer.save()
        return Response({'message': '密码修改成功'}, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class RiskAssessmentListCreateView(generics.ListCreateAPIView):
    """风险评估列表和创建视图"""
    serializer_class = RiskAssessmentSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return RiskAssessment.objects.filter(user=self.request.user)

class RiskAssessmentDetailView(generics.RetrieveUpdateDestroyAPIView):
    """风险评估详情视图"""
    serializer_class = RiskAssessmentSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return RiskAssessment.objects.filter(user=self.request.user)

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def user_stats(request):
    """用户统计信息"""
    user = request.user
    
    # 获取用户的投资组合数量
    from portfolios.models import Portfolio
    portfolio_count = Portfolio.objects.filter(user=user).count()
    
    # 获取用户的风险评估记录数量
    risk_assessment_count = RiskAssessment.objects.filter(user=user).count()
    
    return Response({
        'user_id': user.id,
        'username': user.username,
        'total_assets': user.total_assets,
        'available_cash': user.available_cash,
        'risk_level': user.risk_level,
        'portfolio_count': portfolio_count,
        'risk_assessment_count': risk_assessment_count,
        'investment_experience': user.investment_experience,
        'member_since': user.date_joined
    }, status=status.HTTP_200_OK)
